import express from 'express'
import path from 'path'
import csshook from 'css-modules-require-hook/preset'
import assethook from 'asset-require-hook'

import server_entry from './server-entry'
import staticPath from '../build/asset-manifest.json'

assethook({
  extensions: ['png', 'jpg'],
  publicPath: '/dist/'
})

const app = express()
const PORT = process.env.PORT || 3002;

app.use(function (req, res, next) {
  if(req.url.startsWith('/static/')) {
    return next()
  }
  const obj = {
    '/': '亿创科技'
  }
  res.write(
    `<!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
          <meta name="theme-color" content="#000000">
          <meta name='keywrod' content='亿创科技'>
          <meta name='description' content='${obj[req.url]}'>
          <meta name='author' content='zane'>
          <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
          <link rel="stylesheet" href="${staticPath['main.css']}">
          <title>亿创科技</title>
        </head>
        <body>
          <noscript></noscript>
          <div id="root">
    `
  )
  const markupStream = server_entry(req)
  markupStream.pipe(res, { end: false })
  markupStream.on('end', () => {
    res.write(
      `
            </div>
            <script src="${staticPath['main.js']}"></script>
          </body>
        </html>
      `
    )
    res.end()
  })
})
app.use('/', express.static(path.join(__dirname, '../build')))

app.listen(PORT, function () {
  console.log(`Node app start at port ${PORT}`)
})